<template>
	<view class="container">
		<!-- 蓝色头部 -->
		<view class="header">
			<view class="nav-bar">
				<uni-icons type="left" size="24" color="#fff" @click="goBack"></uni-icons>
				<text class="nav-title">立即预约</text>
			</view>
		</view>

		<!-- 可滚动内容区域 -->
		<scroll-view class="content-scroll" scroll-y>
			<!-- 维修方式 -->
			<view class="repair-method-section">
				<text class="section-label">维修方式</text>
				<view class="radio-group-wrapper">
					<view class="radio-group">
						<view class="radio-item" :class="{ active: repairMethod === 'onsite' }"
							@click="selectRepairMethod('onsite')">
							<view class="radio-circle" :class="{ checked: repairMethod === 'onsite' }"></view>
							<text class="radio-label">到店维修</text>
						</view>
						<view class="radio-item" :class="{ active: repairMethod === 'pickup' }"
							@click="selectRepairMethod('pickup')">
							<view class="radio-circle" :class="{ checked: repairMethod === 'pickup' }"></view>
							<text class="radio-label">上门取车</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 客户信息 -->
			<view class="form-section">
				<text class="section-title">客户信息</text>
				<view class="form-item">
					<view class="form-label">车主姓名</view>
					<view class="form-input-wrapper">
						<input class="form-input" type="text" v-model="formData.ownerName" placeholder="请输入车主姓名" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">联系方式</view>
					<view class="form-input-wrapper">
						<input class="form-input" type="text" v-model="formData.contact" placeholder="请输入联系方式" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">预约时间</view>
					<view class="form-input-wrapper">
						<uni-datetime-picker type="datetime" v-model="formData.appointmentTime" :start="minDate"
							:end="maxDate" :border="false" :clear-icon="false" placeholder="请输入预约时间"
							return-type="string" @change="onTimeChange" class="datetime-picker-custom">
						</uni-datetime-picker>
					</view>
				</view>
				<!-- 上门取车时显示取车位置 -->
				<view class="form-item" v-if="repairMethod === 'pickup'">
					<view class="form-label">取车位置</view>
					<view class="form-input-wrapper">
						<input class="form-input" type="text" v-model="formData.pickupLocation" placeholder="请输入取车位置" />
					</view>
				</view>
			</view>

			<!-- 车辆信息 -->
			<view class="form-section">
				<text class="section-title">车辆信息</text>
				<view class="form-item">
					<view class="form-label">车辆类型</view>
					<view class="form-input-wrapper">
						<picker class="picker-block" mode="selector" :range="vehicleTypes" :value="vehicleTypeIndex"
							@change="onVehicleTypeChange">
							<view class="picker-input">
								<text :class="{ placeholder: vehicleTypeIndex === -1 }">
									{{ vehicleTypeIndex >= 0 ? vehicleTypes[vehicleTypeIndex] : '请选择' }}
								</text>
								<uni-icons type="right" size="16" color="#999"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">车牌号</view>
					<view class="form-input-wrapper">
						<input class="form-input" type="text" v-model="formData.plateNumber" placeholder="请输入车牌号" />
					</view>
				</view>
			</view>

			<!-- 照片 -->
			<view class="form-section">
				<text class="section-title">照片</text>
				<view class="photo-section">
					<text class="photo-label">整车照片:</text>
					<view class="photo-upload">
						<view class="photo-box" v-if="formData.fullVehiclePhoto"
							@click="previewImage(formData.fullVehiclePhoto, 0)">
							<image :src="formData.fullVehiclePhoto" mode="aspectFill" class="photo-image"></image>
							<view class="photo-delete" @click.stop="deletePhoto('fullVehiclePhoto')">
								<uni-icons type="closeempty" size="20" color="#fff"></uni-icons>
							</view>
						</view>
						<view class="photo-box empty" v-else @click="chooseImage('fullVehiclePhoto')">
							<view class="photo-add-icon">
								<uni-icons type="plus" size="40" color="#999"></uni-icons>
							</view>
							<text class="photo-add-text">上传照片</text>
						</view>
					</view>
				</view>
				<view class="photo-section">
					<text class="photo-label">维修部位照片:</text>
					<view class="photo-upload">
						<view class="photo-box" v-if="formData.repairPartPhoto"
							@click="previewImage(formData.repairPartPhoto, 1)">
							<image :src="formData.repairPartPhoto" mode="aspectFill" class="photo-image"></image>
							<view class="photo-delete" @click.stop="deletePhoto('repairPartPhoto')">
								<uni-icons type="closeempty" size="20" color="#fff"></uni-icons>
							</view>
						</view>
						<view class="photo-box empty" v-else @click="chooseImage('repairPartPhoto')">
							<view class="photo-add-icon">
								<uni-icons type="plus" size="40" color="#999"></uni-icons>
							</view>
							<text class="photo-add-text">上传照片</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-button-wrapper">
				<view class="bottom-button">
					<text class="button-text" @click="handleSubmit">提交</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'

	// 维修方式
	const repairMethod = ref('pickup') // 'onsite' 到店维修, 'pickup' 上门取车

	// 表单数据
	const formData = ref({
		ownerName: '',
		contact: '',
		appointmentTime: '',
		pickupLocation: '', // 取车位置（上门取车时使用）
		plateNumber: '',
		fullVehiclePhoto: '',
		repairPartPhoto: ''
	})

	// 车辆类型
	const vehicleTypes = ref(['轿车', 'SUV', 'MPV', '跑车', '其他'])
	const vehicleTypeIndex = ref(-1)

	// 日期范围（使用时间戳，更兼容）
	const minDate = ref(0)
	const maxDate = ref(0)

	// 初始化日期范围
	const initDateRange = () => {
		const now = new Date()
		// 最小日期：今天 00:00:00
		const minDateObj = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
		minDate.value = minDateObj.getTime()

		// 最大日期：一年后的今天 23:59:59
		const maxDateObj = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate(), 23, 59, 59)
		maxDate.value = maxDateObj.getTime()

		console.log('日期范围初始化:', {
			min: new Date(minDate.value).toLocaleString(),
			max: new Date(maxDate.value).toLocaleString()
		})
	}

	// 格式化日期时间显示
	const formatDateTime = (dateTimeStr) => {
		if (!dateTimeStr) return ''
		// 格式化显示：2024-01-01 12:00 -> 2024年01月01日 12:00
		if (typeof dateTimeStr === 'string' && dateTimeStr.includes('-')) {
			const parts = dateTimeStr.split(' ')
			if (parts.length >= 2) {
				const [date, time] = parts
				const [year, month, day] = date.split('-')
				// 格式化时间：12:00 -> 12:00
				const [hours, minutes] = time.split(':')
				return `${year}年${month}月${day}日 ${hours}:${minutes}`
			} else {
				// 只有日期，没有时间
				const [year, month, day] = dateTimeStr.split('-')
				return `${year}年${month}月${day}日`
			}
		}
		return dateTimeStr
	}

	// 选择维修方式
	const selectRepairMethod = (method) => {
		repairMethod.value = method
	}

	// 时间选择
	const onTimeChange = (e) => {
		// uni-datetime-picker 的 change 事件返回选中的值
		console.log('时间选择事件:', e)
		// v-model 会自动同步，这里可以额外处理
		if (e) {
			formData.value.appointmentTime = e
		}
		console.log('选择的预约时间:', formData.value.appointmentTime)
	}

	// 车辆类型选择
	const onVehicleTypeChange = (e) => {
		vehicleTypeIndex.value = e.detail.value
	}

	// 选择图片
	const chooseImage = (type) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0]
				if (type === 'fullVehiclePhoto') {
					formData.value.fullVehiclePhoto = tempFilePath
				} else if (type === 'repairPartPhoto') {
					formData.value.repairPartPhoto = tempFilePath
				}
			},
			fail: (err) => {
				console.error('选择图片失败', err)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				})
			}
		})
	}

	// 预览图片
	const previewImage = (url, index) => {
		const urls = []
		if (formData.value.fullVehiclePhoto) urls.push(formData.value.fullVehiclePhoto)
		if (formData.value.repairPartPhoto) urls.push(formData.value.repairPartPhoto)
		uni.previewImage({
			current: index,
			urls: urls.filter(item => item)
		})
	}

	// 删除图片
	const deletePhoto = (type) => {
		if (type === 'fullVehiclePhoto') {
			formData.value.fullVehiclePhoto = ''
		} else if (type === 'repairPartPhoto') {
			formData.value.repairPartPhoto = ''
		}
	}

	// 表单验证
	const validateForm = () => {
		if (!formData.value.ownerName) {
			uni.showToast({
				title: '请输入车主姓名',
				icon: 'none'
			})
			return false
		}
		if (!formData.value.contact) {
			uni.showToast({
				title: '请输入联系方式',
				icon: 'none'
			})
			return false
		}
		if (!formData.value.appointmentTime) {
			uni.showToast({
				title: '请选择预约时间',
				icon: 'none'
			})
			return false
		}
		// 上门取车时，需要验证取车位置
		if (repairMethod.value === 'pickup' && !formData.value.pickupLocation) {
			uni.showToast({
				title: '请输入取车位置',
				icon: 'none'
			})
			return false
		}
		if (vehicleTypeIndex.value === -1) {
			uni.showToast({
				title: '请选择车辆类型',
				icon: 'none'
			})
			return false
		}
		if (!formData.value.plateNumber) {
			uni.showToast({
				title: '请输入车牌号',
				icon: 'none'
			})
			return false
		}
		return true
	}

	// 提交表单
	const handleSubmit = () => {
		if (!validateForm()) {
			return
		}

		// 准备提交数据
		const submitData = {
			repairMethod: repairMethod.value,
			ownerName: formData.value.ownerName,
			contact: formData.value.contact,
			appointmentTime: formData.value.appointmentTime,
			vehicleType: vehicleTypes.value[vehicleTypeIndex.value],
			plateNumber: formData.value.plateNumber,
			fullVehiclePhoto: formData.value.fullVehiclePhoto,
			repairPartPhoto: formData.value.repairPartPhoto
		}

		// 上门取车时，添加取车位置
		if (repairMethod.value === 'pickup') {
			submitData.pickupLocation = formData.value.pickupLocation
		}

		console.log('提交数据:', submitData)

		// TODO: 调用接口提交数据
		// 模拟提交成功，生成预约编号
		const timestamp = Date.now()
		const appointmentNum = timestamp.toString().slice(-15)
		
		// 跳转到预约成功页面
		uni.redirectTo({
			url: `/pages/repair/fjmd/mdxq/ljyy/yycg/index?number=${appointmentNum}`
		})
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}

	// 获取门店信息
	onMounted(() => {
		// 初始化日期范围
		initDateRange()

		// 可以从路由参数或存储中获取门店信息
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options || {}
		console.log('预约页面参数:', options)
	})
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	/* 蓝色头部 */
	.header {
		width: 100%;
		background-color: #3486fe;
		padding-top: var(--status-bar-height);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 100;
	}

	.nav-bar {
		display: flex;
		/* align-items: center; */
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 300rpx;
		position: relative;
	}

	.nav-title {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		text-align: center;
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		pointer-events: none;
	}

	.nav-right {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-left: auto;
	}

	.nav-icon-dots {
		display: flex;
		gap: 8rpx;
	}

	.nav-icon-dot {
		width: 8rpx;
		height: 8rpx;
		background-color: #fff;
		border-radius: 50%;
	}

	.nav-icon-target {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-icon-circle {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-icon-inner-circle {
		width: 16rpx;
		height: 16rpx;
		background-color: #fff;
		border-radius: 50%;
	}

	/* 可滚动内容区域 */
	.content-scroll {
		flex: 1;
		margin-top: calc(var(--status-bar-height) + 88rpx);
		overflow-y: auto;
		padding: 0;
		z-index: 110;
	}

	/* 维修方式 */
	.repair-method-section {
		background-color: #fff;
		margin: 20rpx 30rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.section-label {
		font-size: 32rpx;
		font-weight: normal;
		color: #333;
		margin: 0;
		margin-right: 40rpx;
		display: block;
		flex-shrink: 0;
		font-weight: bold;
	}

	.radio-group-wrapper {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.radio-group {
		display: flex;
		gap: 40rpx;
		align-items: center;
	}

	.radio-item {
		display: flex;
		align-items: center;
		gap: 12rpx;
		cursor: pointer;
	}

	.radio-circle {
		width: 36rpx;
		height: 36rpx;
		border: 2rpx solid #999;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.radio-circle.checked {
		border-color: #3486fe;
	}

	.radio-circle.checked::after {
		content: '';
		width: 20rpx;
		height: 20rpx;
		background-color: #3486fe;
		border-radius: 50%;
	}

	.radio-label {
		font-size: 28rpx;
		color: #333;
		transition: color 0.3s;
	}

	.radio-item.active .radio-label {
		color: #3486fe;
	}

	/* 表单区域 */
	.form-section {
		background-color: #fff;
		margin: 20rpx 30rpx;
		padding: 30rpx;
		border-radius: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		display: block;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.form-label {
		min-width: 160rpx;
		font-size: 28rpx;
		color: #fff;
		background: linear-gradient(180deg, #72b5ff 0%, #3486fe 100%);
		padding: 16rpx 28rpx;
		border-radius: 999rpx;
		text-align: center;
		flex-shrink: 0;
		margin-right: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.form-input-wrapper {
		flex: 1;
		display: flex;
		align-items: center;
		min-height: 72rpx;
		padding: 0 30rpx;
		background-color: #fff;
		border: 2rpx solid #e6e6e6;
		border-radius: 999rpx;
		box-sizing: border-box;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		height: 72rpx;
		line-height: 72rpx;
		border: none;
		background: transparent;
		padding: 0;
	}

	.form-input:focus {
		outline: none;
	}

	.form-input::placeholder {
		color: #999;
	}

	.picker-block {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.picker-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		height: 100%;
		font-size: 28rpx;
		color: #333;
	}

	.picker-input .placeholder {
		color: #999;
	}

	/* 自定义 uni-datetime-picker 样式 */
	.datetime-picker-custom {
		flex: 1;
		width: 100%;
	}

	:deep(.datetime-picker-custom .uni-datetime-picker) {
		border: none !important;
		width: 100% !important;
	}

	:deep(.datetime-picker-custom .uni-datetime-picker__selector) {
		padding: 0 !important;
		font-size: 28rpx !important;
		color: #333 !important;
		min-height: 72rpx !important;
		display: flex !important;
		align-items: center !important;
	}

	:deep(.datetime-picker-custom .uni-datetime-picker__selector-placeholder) {
		color: #999 !important;
	}

	/* 确保日期时间选择器的弹出层在底部按钮之上（底部按钮z-index是100） */
	/* 时间选择器弹出层（移动端旧版本） */
	:deep(.uni-datetime-picker-mask) {
		z-index: 1000 !important;
	}

	:deep(.uni-datetime-picker-popup) {
		z-index: 1001 !important;
	}

	/* PC端日历弹出层 */
	:deep(.uni-date-mask--pc) {
		z-index: 1000 !important;
	}

	:deep(.uni-date-single--x) {
		z-index: 1001 !important;
	}

	:deep(.uni-date-range--x) {
		z-index: 1001 !important;
	}

	/* 移动端日历弹出层 */
	:deep(.uni-calendar__mask) {
		z-index: 1000 !important;
	}

	:deep(.uni-calendar) {
		z-index: 1001 !important;
	}

	:deep(.uni-calendar__content) {
		z-index: 1001 !important;
	}

	:deep(.uni-calendar--fixed) {
		z-index: 1001 !important;
	}

	/* 确保确认按钮可以点击 */
	:deep(.uni-datetime-picker--btn) {
		z-index: 1002 !important;
		position: relative;
		pointer-events: auto !important;
	}

	:deep(.uni-date-btn--ok) {
		z-index: 1002 !important;
		position: relative;
		pointer-events: auto !important;
	}

	/* 确保弹出层内容区域有足够的底部空间，避免被底部按钮遮挡 */
	:deep(.uni-calendar__content) {
		padding-bottom: 120rpx !important;
		max-height: calc(100vh - 200rpx) !important;
		overflow-y: auto !important;
	}

	:deep(.uni-datetime-picker-popup) {
		max-height: calc(100vh - 200rpx) !important;
		overflow-y: auto !important;
	}

	/* 确保弹出层的按钮区域在底部按钮之上 */
	:deep(.uni-date-changed.uni-calendar--fixed-top) {
		position: sticky !important;
		bottom: 0 !important;
		background-color: #fff !important;
		z-index: 1003 !important;
		padding-bottom: 20rpx !important;
	}

	/* 照片区域 */
	.photo-section {
		margin-bottom: 40rpx;
	}

	.photo-section:last-child {
		margin-bottom: 0;
	}

	.photo-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.photo-upload {
		display: flex;
		margin-left: 150rpx;
	}

	.photo-box {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
		position: relative;
		background-color: #f9f9f9;
	}

	.photo-box.empty {
		border: 1rpx solid #e0e0e0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.photo-image {
		width: 100%;
		height: 100%;
	}

	.photo-delete {
		position: absolute;
		top: 0;
		right: 0;
		width: 48rpx;
		height: 48rpx;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 0 0 0 12rpx;
	}

	.photo-add-icon {
		margin-bottom: 10rpx;
	}

	.photo-add-text {
		font-size: 24rpx;
		color: #999;
	}

	/* 提交按钮容器 */
	.submit-button-wrapper {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 80rpx 60rpx;
		margin-top: 40rpx;
	}

	/* 提交按钮 */
	.bottom-button {
		width: 100%;
		max-width: 590rpx;
		height: 96rpx;
		background-color: #3486fe;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 48rpx;
		box-shadow: 0 12rpx 24rpx rgba(52, 134, 254, 0.25);
	}

	.button-text {
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
	}
</style>